{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\n# Use Tensorize to Leverage Hardware Intrinsics\n**Author**: [Yizhi Liu](https://github.com/yzhliu)\n\nThis is an introduction material on how to perform tensorization in TVM.\n\nBy using schedule primitive :code:`tensorize`,\npeople can replace a unit of computation with the corresponding intrinsics,\nmaking it easy to leverage handcrafted micro-kernels,\nas well as extend TVM to support new hardware architectures.\n\nThe purpose of this tutorial is to show the functionality\nand usage of tensorize instead of providing an efficient solution.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from __future__ import absolute_import, print_function\n\n\nimport tvm\nfrom tvm import te\nimport tvm.testing\nimport numpy as np"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Define Matrix Multiplication\nTake matrix multiplication as our example.\nMatmul first multiply the corresponding elements between two matrix,\nthen accumulate across a certain axis.\nThe following lines describe the computation :code:`A * B^T` in TVM.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "N, M, L = 1024, 512, 64\nA = te.placeholder((N, L), name=\"A\")\nB = te.placeholder((M, L), name=\"B\")\nk = te.reduce_axis((0, L), name=\"k\")\nC = te.compute((N, M), lambda i, j: te.sum(A[i, k] * B[j, k], axis=k), name=\"C\")\ns = te.create_schedule(C.op)\nprint(tvm.lower(s, [A, B, C], simple_mode=True))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Schedule the Matmul\nNow, suppose we have an accelerator that supports\nmatrix-vector multiplication (GEMV) as a hardware primitive,\nwhich can take arbitrary size of reduce axis,\nbut another axis needs to be no larger than 16.\nThus we break down the matmul loops to make the innermost loops a (16x64) GEMV.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "factor = 16\nx, y = C.op.axis\n(z,) = C.op.reduce_axis\nyo, yi = s[C].split(y, factor=factor)\ns[C].reorder(x, yo, yi, z)\nprint(tvm.lower(s, [A, B, C], simple_mode=True))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As showed in the IR printed above,\nthe inner loops :code:`j.inner` along with :code:`k` together form a computation of GEMV\n- within the inner most two loops, the index :code:`i` is fixed,\nthe access to the matrix :code:`A` only varies by :code:`k`,\nwhich makes the access pattern of :code:`A` a \"vector\".\nIn order to leverage our hypothetical hardware's GEMV instruction,\nwe can tensorize over :code:`j.inner`.\n\n## Define GEMV Tensorization Intrinsic\nBefore scheduling the tensorization, we need to first define the intrinsic function for GEMV.\nIt includes two parts, the first is a compute definition of GEMV.\nTVM uses it to match the computing pattern in the original Matmul schedule.\nThe second is to specify how to execute GEMV on the device,\nwhich is done in :code:`intrin_func` below.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def intrin_gemv(m, l):\n    a = te.placeholder((l,), name=\"a\")\n    b = te.placeholder((m, l), name=\"b\")\n    k = te.reduce_axis((0, l), name=\"k\")\n    c = te.compute((m,), lambda i: te.sum(a[k] * b[i, k], axis=k), name=\"c\")\n    Ab = tvm.tir.decl_buffer(a.shape, a.dtype, name=\"A\", offset_factor=1, strides=[1])\n    Bb = tvm.tir.decl_buffer(b.shape, b.dtype, name=\"B\", offset_factor=1, strides=[te.var(\"s1\"), 1])\n    Cb = tvm.tir.decl_buffer(c.shape, c.dtype, name=\"C\", offset_factor=1, strides=[1])\n\n    def intrin_func(ins, outs):\n        ib = tvm.tir.ir_builder.create()\n        aa, bb = ins\n        cc = outs[0]\n        ib.emit(\n            tvm.tir.call_extern(\n                \"int32\",\n                \"gemv_update\",\n                cc.access_ptr(\"w\"),\n                aa.access_ptr(\"r\"),\n                bb.access_ptr(\"r\"),\n                m,\n                l,\n                bb.strides[0],\n            )\n        )\n        return ib.get()\n\n    return te.decl_tensor_intrin(c.op, intrin_func, binds={a: Ab, b: Bb, c: Cb})"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Here :code:`te.decl_tensor_intrin` declares how to execute the computation :code:`c.op`.\nOur implementation simply takes the inputs and outputs,\nconverts them to pointers and emit an external function call.\nNote that tensorization requires user to specify :code:`offset_factor`,\nwith this information, TVM has knowledge of whether the data is aligned\nbetween the start address of the original data structure\nand the offset being passed to tensorize,\nso that it has chance to optimize with vectorized loading.\nWe set the factor to 1 for simplification.\n\nBuffers are also declared for inputs and outputs, though this is not required,\nwe benefit from the extra information provided by buffers. For example, we pass\n:code:`bb.strides[0]` as an argument to the external function :code:`gemv_update`.\nFor now :code:`bb.strides[0] == l`,\nbut later we will see how they can differ with more complicated schedules.\n\nNote that we use :code:`te.var(\"s1\")` as the first stride dimension for :code:`B`.\nIf the strides can be inferred\n- in this case, TVM knows tensor B is compact thus the strides are :code:`[L, 1]` -\nsuch placeholder can be put to let TVM automatically bind the inferred value for us.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "gemv = intrin_gemv(factor, L)\ns[C].tensorize(yi, gemv)\nprint(tvm.lower(s, [A, B, C], simple_mode=True))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "By tensorizing over :code:`yi`, the inner most two loops are\nnow replaced by the intrinsic function we defined before.\nIn order to build and run the module, let's define the external function :code:`gemv_update`,\nit is a naive implementation of GEMV, just for demonstration.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def gemv_impl():\n    cc_code = \"\"\"\n      extern \"C\" int gemv_update(float *cc, float *aa, float *bb, int m, int l, int stride) {\n        for (int i = 0; i < m; ++i) {\n            for (int j = 0; j < l; ++j) {\n                cc[i] += aa[j] * bb[i * stride + j];\n            }\n        }\n        return 0;\n      }\n    \"\"\"\n    from tvm.contrib import utils, clang\n\n    temp = utils.tempdir()\n    ll_path = temp.relpath(\"temp.ll\")\n    # Create LLVM ir from c source code\n    ll_code = clang.create_llvm(cc_code, output=ll_path)\n    return ll_code"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now we leverage the pragma attribute :code:`import_llvm` to import llvm asm inline.\nThe importing needs to happen before the tensorized GEMV being executed.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "s[C].pragma(x, \"import_llvm\", gemv_impl())\nprint(tvm.lower(s, [A, B, C], simple_mode=True))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Finally we compare the tensorize version with that :code:`numpy.dot` produces,\nensure our implementation is correct.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "func = tvm.build(s, [A, B, C], target=\"llvm\", name=\"gemv\")\n\nfrom tvm.topi.utils import get_const_tuple\n\ndtype = A.dtype\ndev = tvm.device(\"cpu\", 0)\na = np.random.uniform(size=get_const_tuple(A.shape)).astype(dtype)\nb = np.random.uniform(size=get_const_tuple(B.shape)).astype(dtype)\nc = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=dtype), dev)\nfunc(tvm.nd.array(a, dev), tvm.nd.array(b, dev), c)\ntvm.testing.assert_allclose(c.numpy(), np.dot(a, b.T), rtol=1e-3)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Reduce-update for Tensorize\nSo far you have learned the basic idea of tensorize,\nnow let's move one step forward to a more complicated case.\n\nAssume our accelerator could only multiply a vector by a square matrix,\nin which the vector size needs to be no larger than 16.\nGiven such hardware constrain, now we need to split the reduce axis as following,\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "zo, zi = s[C].split(z, factor=factor)\ns[C].reorder(x, yo, zo, yi, zi)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "However, since the tensorize intrinsic now only covers a part of the reduce axis,\ninstead of using one \"body\" function, TVM requires a :code:`reduce_reset` function,\nwhich will be invoked before the reduce for-loop, and a :code:`reduce_update` function,\nwhich defines the \"update\" computing strategy.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def gemv_impl():\n    cc_code = \"\"\"\n      extern \"C\" int gemv_update(float *cc, float *aa, float *bb, int m, int l, int stride) {\n        for (int i = 0; i < m; ++i) {\n            for (int j = 0; j < l; ++j) {\n                cc[i] += aa[j] * bb[i * stride + j];\n            }\n        }\n        return 0;\n      }\n      extern \"C\" int gemv_reset(float *cc, int m) {\n        for (int i = 0; i < m; ++i) {\n            cc[i] = 0.0;\n        }\n        return 0;\n      }\n    \"\"\"\n    from tvm.contrib import utils, clang\n\n    temp = utils.tempdir()\n    ll_path = temp.relpath(\"temp.ll\")\n    # Create LLVM ir from c source code\n    ll_code = clang.create_llvm(cc_code, output=ll_path)\n    return ll_code\n\n\ndef intrin_gemv(m, l):\n    a = te.placeholder((l,), name=\"a\")\n    b = te.placeholder((m, l), name=\"b\")\n    k = te.reduce_axis((0, l), name=\"k\")\n    c = te.compute((m,), lambda i: te.sum(a[k] * b[i, k], axis=k), name=\"c\")\n    Ab = tvm.tir.decl_buffer(a.shape, a.dtype, name=\"A\", offset_factor=1, strides=[1])\n    Bb = tvm.tir.decl_buffer(b.shape, b.dtype, name=\"B\", offset_factor=1, strides=[te.var(\"s1\"), 1])\n    Cb = tvm.tir.decl_buffer(c.shape, c.dtype, name=\"C\", offset_factor=1, strides=[1])\n\n    def intrin_func(ins, outs):\n        aa, bb = ins\n        cc = outs[0]\n\n        def _body():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_extern(\n                    \"int32\",\n                    \"gemv_update\",\n                    cc.access_ptr(\"w\"),\n                    aa.access_ptr(\"r\"),\n                    bb.access_ptr(\"r\"),\n                    m,\n                    l,\n                    bb.strides[0],\n                )\n            )\n            return ib.get()\n\n        def _reduce_reset():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(tvm.tir.call_extern(\"int32\", \"gemv_reset\", cc.access_ptr(\"w\"), m))\n            return ib.get()\n\n        def _reduce_update():\n            return _body()\n\n        return _body(), _reduce_reset(), _reduce_update()\n\n    return te.decl_tensor_intrin(c.op, intrin_func, binds={a: Ab, b: Bb, c: Cb})"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Note that :code:`intrin_func` now returns a triplet:\n:code:`(body, reduce_reset, reduce_update)`.\nIf tensorization includes all the reduce axes, function :code:`body()` will be invoked,\notherwise :code:`reduce_reset()` and :code:`reduce_update()` together will be used.\nIn our example :code:`body()` and :code:`reduce_update()`\nshare the same implementation,\nwhile in other cases, hardware may have different instructions for these two functions.\nMoreover, we can see now :code:`bb.strides[0]` is different from :code:`l`\ndue to the tiling.\n\nTensorize for squared GEMV, build and check the results,\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "gemv = intrin_gemv(factor, factor)\ns[C].tensorize(yi, gemv)\ns[C].pragma(yo, \"import_llvm\", gemv_impl())\n\nfunc = tvm.build(s, [A, B, C], target=\"llvm\", name=\"gemv\")\na = np.random.uniform(size=get_const_tuple(A.shape)).astype(dtype)\nb = np.random.uniform(size=get_const_tuple(B.shape)).astype(dtype)\nc = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=dtype), dev)\nfunc(tvm.nd.array(a, dev), tvm.nd.array(b, dev), c)\ntvm.testing.assert_allclose(c.numpy(), np.dot(a, b.T), rtol=1e-3)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Summary\nThis tutorial demonstrates the usage of tensorize intrinsic in TVM.\nTensorize provides a way for users to get fully optimized schedule via micro-kernels.\nFor example, INT8 quantization on Intel CPUs uses tensorization\nto invoke AVX instruction directly.\nIt also enables TVM to compile to ASICs -\ncheckout `vta-index` for details.\nWe also demonstrates how to use inline assembly importing,\nwhich helps users inject asm easily into the schedule.\n\n\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.5"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}